package tur.br.moradadosol.view.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

import tur.br.moradadosol.control.ApartamentoControl;
import tur.br.moradadosol.control.UserAutentication;
import tur.br.moradadosol.view.form.ApartamentoForm;

public class ApartamentoAction extends Action {

	public ActionForward execute(
		ActionMapping mapping,
		ActionForm form,
		HttpServletRequest request,
		HttpServletResponse response)
		throws Exception {
		
		HttpSession session = request.getSession();
		
		if(!UserAutentication.isUserAutenticated(session)) {
			return mapping.findForward("login");
		}
		
		ActionMessages errors = new ActionMessages();
		
		ApartamentoForm Form = (ApartamentoForm) form;
		
		ApartamentoControl fApartamento = 
			(ApartamentoControl) session.getAttribute("fApartamento");
		if(fApartamento == null) {
			fApartamento = new ApartamentoControl();
			session.setAttribute("fApartamento", fApartamento);
		}
		
		try {
			if(Form.getGravar().length() > 0) {
				fApartamento.gravar(Form.getApartamento());
				Form.setAltcodigo(Form.getApartamento().getCodigo());
				
				errors.add("apartamento.error", new ActionMessage(
				"message.operation.sucess"));
			}
			else if(Form.getCancelar().length() > 0) {
				Form.resetForm(mapping, request);
			}
			else if(Form.getDeletar().length() > 0) {
				fApartamento.delete(Form.getCodigo());
				Form.resetForm(mapping, request);
				errors.add("apartamento.error", new ActionMessage(
				"message.operation.sucess"));
			}
			else if(Form.getAltcodigo() != Form.getCodigo() 
				&& Form.getAltcodigo() > 0) {
				Form.setApartamento(fApartamento.getApartamentoByCodigo(
					Form.getAltcodigo()));
			}
			else if(Form.getAltcodigo() == 0) {
				Form.resetForm(mapping, request);
			}
		}
		catch (Exception e) {
			errors.add("error.apartamento", new ActionMessage(e.getLocalizedMessage()));
		}
		
		if (!errors.isEmpty()) {
			saveErrors(request, errors);
		}
		
		fApartamento.loadApartamentos();

		return mapping.getInputForward();

	}
}
